package com.cosmo.integration.service;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPut;

import com.cosmo.integration.web.HttpResponseResult;

public class CmpServiceImpl extends BaseService implements CmpService {

    private final Log logger = LogFactory.getLog(getClass());

	public CmpServiceImpl(String serviceBaseScheme, String serviceBaseHost,
			int serviceBasePort, String serviceBasePath,
            HttpClient httpClient, Map<String, String> namespaces,
            String serviceFrontUrl) {

		super(serviceBaseScheme, serviceBaseHost, serviceBasePort, serviceBasePath, httpClient, namespaces, serviceFrontUrl);
	}

	/*
	* http://chandlerproject.org/Projects/CosmoManagementProtocol#Creating%20A%20User%20Account
	* requests seems to be text/xml - our standard
    * 201 (Created) - the user account was created in its entirety
    * 400 (Bad Request) - the XML representation was improperly constructed, an attribute value was missing or invalid, or the username specified in the XML does not match the username in the request URI
    * 431 (Username In Use) - the specified user name is already used by an existing account
    * 432 (Email In Use) - the specified email address is already used by an existing account 
    */
	public void createUser(String username) {
        String createTemplate = "<?xml version='1.0' encoding='UTF-8'?>" +
        						"<user xmlns=\"http://osafoundation.org/cosmo/CMP\">" +
        						"<username>TEMPLATE_USERNAME</username>" +
        						"<password>med45</password>" +
        						"<email>user@email</email>" +
        						"<administrator>false</administrator>" +
        						"</user>";
		String body = createTemplate.replace("TEMPLATE_USERNAME", username);
		String path = getServiceBasePath() + "/user/" + username;
		HttpPut put = createPut(getServiceBaseScheme(), getServiceBaseHost(), getServiceBasePort(), path, body, null);
		// false - we want to throw exceptions from the services
		HttpResponseResult result = sendReceive(put, false);
		logger.info("response: \n" + result.getResponseBody());
    }

}

